import {
  Following,
  getUerInfo,
  getUserProfile,
  patchUserPhoto,
  patchUserProfile,
  TPatchUserProfile,
  TUserInfo,
  TUserProfile,
  unFollowing
} from '@/api'
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'
import { getArticleByIdAction } from './article'

// 获取用户自己信息的Action
export const UserInfoAction = createAsyncThunk('profile/UserInfo', async () => {
  try {
    const res = await getUerInfo()
    console.log('res', res)
    return res.data.data
  } catch (error) {}
})

//  获取用户个人资料的Action
export const UserProfileAction = createAsyncThunk(
  'profile/UserProfile',
  async () => {
    try {
      const res = await getUserProfile()
      return res.data.data
    } catch (error) {}
  }
)

// 编辑用户个人资料
export const patchUserProfileAction = createAsyncThunk(
  'profile/patchUserProfile',
  async (data: TPatchUserProfile) => {
    try {
      await patchUserProfile(data)
      const res = await getUserProfile()
      return res.data.data
    } catch (error) {}
  }
)

// 编辑用户照片资料（头像、身份证照片）
export const UserPhotoAction = createAsyncThunk(
  'profile/UserPhoto',
  async (data: FormData) => {
    try {
      const res = await patchUserPhoto(data)
      console.log('res', res)
      return res.data.data
    } catch (error) {}
  }
)
// 编辑用户照片资料（头像、身份证照片）
export const FollowingAction = createAsyncThunk(
  'profile/Following',
  async (data: { art_id: string; aut_id: string }, state) => {
    try {
      await Following(data.aut_id)
      await state.dispatch(getArticleByIdAction(data.art_id))
    } catch (error) {}
  }
)
// 编辑用户照片资料（头像、身份证照片）
export const unFollowingAction = createAsyncThunk(
  'profile/unFollowing',
  async (data: { art_id: string; aut_id: string }, state) => {
    try {
      await unFollowing(data.aut_id)
      await state.dispatch(getArticleByIdAction(data.art_id))
    } catch (error) {}
  }
)

export interface IProfile {
  info: TUserInfo
  profile: TUserProfile
}
const initialState: IProfile = {
  info: {} as TUserInfo,
  profile: {} as TUserProfile
}

export const profileSlice = createSlice({
  name: 'profile',
  initialState,
  reducers: {},
  extraReducers: {
    [UserInfoAction.fulfilled.type]: (
      state,
      action: PayloadAction<TUserInfo>
    ) => {
      state.info = action.payload
    },
    [UserProfileAction.fulfilled.type]: (
      state,
      action: PayloadAction<TUserProfile>
    ) => {
      state.profile = action.payload
    },
    [patchUserProfileAction.fulfilled.type]: (
      state,
      action: PayloadAction<TUserProfile>
    ) => {
      state.profile = action.payload
    },
    [UserPhotoAction.fulfilled.type]: (
      state,
      action: PayloadAction<{ photo: string }>
    ) => {
      state.profile.photo = action.payload.photo
    }
  }
})
// Action creators are generated for each case reducer function
// export const { } = profileSlice.actions

export default profileSlice.reducer
